package com.gq.matmadavinci;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.gq.utils.MyViewPager;
import com.gq.utils.NetworkState;
import com.rtst.widget.actionbar.ActionBarActivity;

public class ReaderActivity extends ActionBarActivity implements OnTouchListener {

	private MyViewPager viewPager;
	private int mPosition;
	private AdView adView;
	private Handler mHandler;
	private ImageView nextBtn, prevBtn;
	private TextView pageNum;
	public static final int NUMBER_OF_PAGES = 123;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reader_scr);
		new NetworkState(ReaderActivity.this).check();
		mHandler = new Handler();
//		mPosition = getIntent().getExtras().getInt("POSITION");
		viewPager = (MyViewPager) findViewById(R.id.viewPager);
		viewPager.setPagingEnable(false);
		adView = (AdView) findViewById(R.id.adView);
		pageNum = (TextView) findViewById(R.id.pageNum);
//		MainActivity.getInstance().trackPageView("vova/detail-"+String.valueOf(mPosition));
		final ReaderAdapter adapter = new ReaderAdapter();
		viewPager.setAdapter(adapter);
		
		nextBtn = (ImageView) findViewById(R.id.btnNext);
		prevBtn = (ImageView) findViewById(R.id.btnPrevious);
		nextBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mHandler.removeCallbacks(mHideButtonRun);
				mHandler.postDelayed(mHideButtonRun, 3000);
				if (mPosition<adapter.getCount()-1) viewPager.setCurrentItem(mPosition+1);
			}
		});
		prevBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mHandler.removeCallbacks(mHideButtonRun);
				mHandler.postDelayed(mHideButtonRun, 3000);
				if (mPosition>0) viewPager.setCurrentItem(mPosition-1);
			}
		});
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				updateButtonState(position, adapter);
//				setLastPage(position);
				if (position>0) {
					pageNum.setVisibility(View.VISIBLE);
					pageNum.setText(String.format("Trang %d/%d", position, NUMBER_OF_PAGES));
				} else {
					pageNum.setVisibility(View.GONE);
				}
				mPosition = position;
				if (adView != null) {
					adView.loadAd(new AdRequest());
				}
//				MainActivity.getInstance().trackPageView("vova/detail-"+String.valueOf(mPosition));
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			}
			
			@Override
			public void onPageScrollStateChanged(int position) {
			}
		});
		viewPager.setCurrentItem(getLastPage());
		updateButtonState(0, adapter);
	}
	
	public void setLastPage(int pos) {
		SharedPreferences sharePreference = getPreferences(MODE_PRIVATE);
		Editor editor = sharePreference.edit();
		editor.putInt("lastvisit", pos);
		editor.commit();
	}
	
	public int getLastPage() {
		SharedPreferences sharePreference = getPreferences(MODE_PRIVATE);
		return sharePreference.getInt("lastvisit", 0);
	}
	
	public void updateButtonState(int pos, ReaderAdapter adapter) {
		if (!adapter.canGoNext(pos)) { nextBtn.setVisibility(View.GONE); } else {
			nextBtn.setVisibility(View.VISIBLE);
		}
		if (!adapter.canGoPrev(pos)) prevBtn.setVisibility(View.GONE); else {
			prevBtn.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		adView.loadAd(new AdRequest());
		mHandler.postDelayed(mHideButtonRun, 3000);
	}

	@Override
	protected void onDestroy() {
		if (adView != null) adView.destroy();
		super.onDestroy();
	}
	
	private Runnable mHideButtonRun = new Runnable() {
		public void run() {
			nextBtn.setVisibility(View.GONE);
			prevBtn.setVisibility(View.GONE);
			pageNum.setVisibility(View.GONE);
		}
	};
	

	private class ReaderAdapter extends PagerAdapter {

		private static final int MAX_PAGE = NUMBER_OF_PAGES + 1;
		
		@Override
		public int getCount() {
			return MAX_PAGE;
		}
		
		public boolean canGoNext(int currentPos) {
			return currentPos < MAX_PAGE;
		}
		
		public boolean canGoPrev(int currentPos) {
			return currentPos > 0;
		}
		
		public String getItem(int position) {
			try {
				return String.format("%d.html", position);
			} catch(Exception e) {
			}
			return null;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == (View) object;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public Object instantiateItem(View container, int position) {
			
			if (position == 0) {
				LayoutInflater mInflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				ViewGroup viewGroup = (ViewGroup) mInflate.inflate(R.layout.intro_scr, null, false);
				((ViewPager) container).addView(viewGroup);
				viewGroup.setOnTouchListener(ReaderActivity.this);
				return viewGroup;
			}
			WebView webView = new WebView(ReaderActivity.this);
			webView.setOnTouchListener(ReaderActivity.this);
			String item = getItem(position);
			if (item != null) {
//				String html = getAssetHtml(item);
//				webView.loadData(html, "text/html", "utf-8");
				webView.loadUrl(String.format("file:///android_asset/%s", item));
			}
			((ViewPager) container).addView(webView);
			return webView;
		}
		
		public String getAssetHtml(String fileName) {
			StringBuilder sb = new StringBuilder();
			InputStream is = null;
			try {
				is = getAssets().open(fileName);
				int byteRead = 0;
				byte[] buff = new byte[1024];
				while((byteRead = is.read(buff)) != -1) {
					sb.append(new String(buff, 0, byteRead));
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (is != null) try { is.close(); } catch(Exception e) {}
			}
			return sb.toString();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.read, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			//Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show();
			break;
		
		case R.id.menu_info:
//			startActivity(new Intent(this, MoreAppActivity.class));
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://search?q=pub:Viet Android JSC"));
			startActivity(intent);
			break;
		
		case R.id.menu_gotopage:
			AlertDialog.Builder gotoBuilder = new AlertDialog.Builder(this);
			gotoBuilder.setInverseBackgroundForced(true);
			String[] pg = new String[viewPager.getAdapter().getCount() - 1];
			for (int i=0;i<pg.length;i++) {
				pg[i] = "Trang " + String.valueOf(i+1);
			}
			gotoBuilder.setItems(pg, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int position) {
					if (position>=0 && position<viewPager.getAdapter().getCount()-1) viewPager.setCurrentItem(position+1);
					dialog.dismiss();
				}
			});
			gotoBuilder.create().show();
			break;
			
		case R.id.menu_save:
			AlertDialog.Builder builder = new AlertDialog.Builder(ReaderActivity.this);
			builder.setMessage("Bạn muốn lưu lại trang hiện tại?")
			.setCancelable(true)
			.setPositiveButton("Có", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					setLastPage(mPosition);
					dialog.cancel();
				}
			})
			.setNegativeButton("Không", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onTouch(View v, MotionEvent evt) {
		final int action = evt.getAction();
		switch(action & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				nextBtn.setVisibility(View.VISIBLE);
				prevBtn.setVisibility(View.VISIBLE);
				pageNum.setVisibility(View.VISIBLE);
				break;
			case MotionEvent.ACTION_UP:
				mHandler.removeCallbacks(mHideButtonRun);
				mHandler.postDelayed(mHideButtonRun, 2000);
				break;
		}
		return false;
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Bạn muốn đóng ứng dụng ?")
		.setCancelable(true)
		.setPositiveButton("Có", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				onDestroy();
				System.runFinalizersOnExit(true);
				System.exit(0);
			}
		})
		.setNegativeButton("Không", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}
	
	
}
